var rqcfg = require('./constant');
const {promisefy } = require('./util');
const bgMusicAudioContext = wx.getBackgroundAudioManager();
// 封装wx request

module.exports = {
  http(config){
    let that = this;
    let request = promisefy(wx.request); //从util取的promisefy，挂载到app.js上
    return request({
      url : that.globalData.requestUrl,
      ...config
    })
  },
  // 获取未付款的订单数
  getNoPay(data){
    return this.http({
      data:{
        map:'applet_member_order_wait',
        ...data
      }
    }).catch(err=>{
      console.error('applet_member_order_wait接口出错：',err);
    });
  },
  // 设置订单的红点
  setOrderMark(){
    return this.getNoPay().then(res=>{
      if(res.data.ec==200){
        let count = res.data.data.count;
        if(count>0){
          wx.showTabBarRedDot({
            index:2           //索引从0开始
          })
          return;
        }
        wx.hideTabBarRedDot({index:2})
      }
    }).catch(err=>{
      console.error('设置订单红点出错：',err);
    })
  },
  //传递错误信息到后台
  postError: function (error) {
    var that = this;
    var mobileInfo;
    var suid = that.globalData.suid ? that.globalData.suid : '';
    var appid = that.globalData.appid ? that.globalData.appid : '';
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        mobileInfo = res;
      }
    });
    var currentPage = getCurrentPages() ? getCurrentPages()[getCurrentPages().length - 1].route : ''; //获取当前页面链接
    console.log('获取当前页面链接');
    console.log(currentPage);
    var data = {};
    data.map = "applet_error_log";
    data.type = "营销商城";
    data.suid = suid;
    data.appid = appid;
    data.brand = mobileInfo.brand;
    data.model = mobileInfo.model;
    data.wxVersion = mobileInfo.version;
    data.SDKVersion = mobileInfo.SDKVersion;
    data.system = mobileInfo.system;
    data.error = error;
    data.currentPage = currentPage;
    console.log(data);
    wx.request({
      url: that.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log('错误发送成功');
          console.log(res.data);
        } else {
          console.log(res);
        }
      },
      fail: function () {
        console.log('失败');
      }
    });
  },
  //成为分销商
  requestdistributionInfo: function (mid) {
    var that = this;
    console.log('成为分销商');
    console.log(mid);
    var data = {};
    data.map = 'applet_three_set_level_new';
    data.mid = mid;
    console.log(data);
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: that.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log('分销商信息',res.data);
        if (res.data.ec == 200) {
        } else {
          that.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  getNavheight:function(){
    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.globalData.statusBarHeight = res.statusBarHeight;
        this.globalData.navHeight = res.statusBarHeight + 46;
        console.log(this.globalData.navHeight + '////////' + res.statusBarHeight)
      }, fail(err) {
        console.log(err);
      }
    })
  },
  isLogin:function(e){
    var _this = this;
    var path = '', jumpUrl='';
    if(e&&e.path){
      var pathQuery = '?';
      for(var key in e.query){
        pathQuery += key + '='+e.query[key]+'&';
      }
      path = e.path + pathQuery;
      path = '/'+path.substr(0,path.length-1);
      console.log(path);
      jumpUrl = path;
      path = encodeURIComponent(path);
    }
    // 判断是否验证
    var data = {
      map: 'applet_start_page'
    }
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data.data);
        var applyInfo = res.data.data;
        if (res.data.data.applyOpen == 1 && applyInfo.applyStatus!=2) {
          wx.reLaunch({
            url: '/pages/login/login?url='+path,
          })
        }else{
          _this.globalData.nologin = 1;
        }
      },
      fail: function (res) {
        console.log(res.data);
      },
    });
  },
 
  getNewRequestUrl:function(mid){
    var _this = this;
    var newUrl = rqcfg.rqcfg.rqurl;
    console.log("原链接----" + newUrl);
    var plumSession =_this.globalData.plumSession;
    newUrl = rqcfg.rqcfg.rqurl + '&plum_session_applet=' + plumSession;
    if(mid){
      newUrl+='&mid='+mid;
    }
    console.log("旧请求链接----" + _this.globalData.requestUrl);
    console.log("新请求链接----" + newUrl);
    return newUrl;
  },
  getPoint:function(that){
    var _this = this;
    setTimeout(function(){
      wx.request({
        url: _this.globalData.requestUrl,
        data: {
          map: 'applet_share_get_point'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            if (res.data.data.msg) {
              console.log(res.data.data.msg);
              wx.showModal({
                title: '',
                content: res.data.data.msg,
                showCancel: false
              })
            }
          } else {
            if (res.data.em) {
              wx.showModal({
                title: '',
                content: res.data.em,
                showCancel: false
              })
            }
          }
        },
        complete: function () {
        }
      });
    },3000)
  },
  errorTip: function (that, text, timer){
    console.log(that);
    that.setData({
      errorTip: {
        text: text,
        isShow: true
      }
    })
    setTimeout(function () {
      that.setData({
        errorTip: {
          text: '',
          isShow: false
        }
      })
    }, timer)
  },
  wechatSq: function (obj,e,val) {
    console.log("发起登录请求，以下是打印值=======", obj, e, val);
    var that = this;
    if (obj && obj.page) {
      that.globalData.requestQueue.push(obj);
    }
    if (val && val.parameter) { // 临时保存数据
        that.globalData.temporaryParameter = val
    }
    if (that.globalData.isLogining) return;  //若是正在登录

    that.globalData.isLogining = true;
    wx.showLoading({
      title: '加载中',
    })
    console.log('登录接口')
    wx.login({
      success: function (res) {
        console.log(res);
        var code = res.code;
        if (res.code) {
          var data = {
            map: 'applet_member_info',
            code: code,
            slient: 1,
            form_source: e.form_source || e.query.form_source
          }
          console.log('登录参数值请求发送', data);
          wx.request({
            url: rqcfg.rqcfg.rqurl,
            data: data,
            success: function (res) {
              that.globalData.isLogining = false;
              if (res.data.ec == 200) {
                console.log("获取用户信息成功");
                that.globalData.isdistrib = res.data.data.isdistrib;
                that.globalData.isapply = res.data.data.isapply;
                that.globalData.requestUrl = rqcfg.rqcfg.rqurl + '&plum_session_applet=' + res.data.data.plum_session_applet;
                console.log(that.globalData.requestUrl);
                wx.setStorage({
                  key: "plumSession",
                  data: res.data.data.plum_session_applet,
                  success: function () {
                    that.globalData.plumSession = res.data.data.plum_session_applet;
                  }
                })
                that.globalData.plumSession = res.data.data.plum_session_applet;
                that.globalData.slient = res.data.data.slient;
                that.globalData.isHasunionid = res.data.data.haveUnionid;
                that.globalData.haveVcmCard = res.data.data.haveVcmCard;
                //由于这里是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (that.plumSessionCallback) {
                  that.plumSessionCallback(res.data.data.plum_session_applet);
                } 
                
                if (that.globalData.userInfo) {
                  typeof cb == "function" && cb(this.globalData.userInfo)
                } else {
                  var defaultAvatar = 'http://tiandiantong.oss-cn-beijing.aliyuncs.com/images/icon_photo.png';
                  res.data.data.avatar = res.data.data.avatar ? res.data.data.avatar : defaultAvatar;
                  res.data.data.nickname = res.data.data.nickname ? res.data.data.nickname : '用户昵称';
                  that.globalData.userInfo = res.data.data;
                  typeof cb == "function" && cb(that.globalData.userInfo)
                }
                console.log(that.globalData.userInfo);
                if (res.data.data.haveUnionid==0){   //如果未获取到unionId
                  wx.getUserInfo({
                    success(res){
                      console.log('已经授权可以直接获取用户信息',res);
                      that.getUnionid('', res);
                    },
                    fail(res){
                      console.log('用户还未授权');
                    }
                  })
                }
                if (obj) {
                  console.log("当前请求值==", e, val);
                  if (e) {
                    if(e=='mid'){
                      obj.requestdistributionInfo(val);
                    }else{
                      let pathReturnLogin = [
                        'pages/becomePartners/becomePartners'
                      ];
                      if (pathReturnLogin.indexOf(e.path) != -1 && that.globalData.plumSession) {
                        console.log(e.path + "?" + that.globalData.temporaryParameter.parameter);
                          wx.navigateTo({
                            url: "/" + e.path + "?" + that.globalData.temporaryParameter.parameter,
                          })
                      }
                      obj.onShow(e);
                    }
                  } else {
                    // obj.onShow();
                    // obj.onLoad();
                    let requestQueue = that.globalData.requestQueue ? that.globalData.requestQueue : [];
                    if (requestQueue.length > 0) {
                      for (let fun of requestQueue) {
                        console.log(fun)
                        let pointer = fun.page;
                        let fname = fun.fname;
                        pointer[fname]()
                      }
                      that.globalData.requestQueue = []
                    }
                  }
                };
                that.requestIndex();
                that.getContactCfg();//客服配置

                setTimeout(function(){ //2s之后获取订阅消息模板id
                  that.getTmplIds();
                },1000)

              } else {
                console.log(res.data);
                console.log("获取用户信息失败");
                
                if(that.globalData.sessionFailNum<3){
                  var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针
                  that.globalData.sessionFailNum = that.globalData.sessionFailNum+1;
                  console.log('获取用户信息失败次数', that.globalData.sessionFailNum);
                  that.wechatSq(page);
                  
                }else{
                  var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针
                  page.setData({
                    loginFail: true
                  })
                  that.postError(res.data.em + '登陆' + that.globalData.sessionFailNum + '次失败'); //错误发送
                }
          
     
              }               
            },
            fail(){
              var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针
              page.setData({
                loginFail: true
              })
            },
            complete: function () {
              console.log("执行完成");
               wx.hideLoading();
              
            }
          });
        } else {
          wx.showToast({
            title: '获取用户登录态失败！' + res.errMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '用户code获取失败！' + res.errMsg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  getTmplIds:function(){
    this.globalData.requestTmplIds = [];
    // var that = this;
    // wx.request({
    //   url: that.globalData.requestUrl,
    //   data: {
    //     map:'applet_subscribe_get_ids_all'
    //   },
    //   success: function (res) {
    //     if (res.data.ec == 200) {
    //       console.log('订阅消息', res.data.data);
    //       that.globalData.requestTmplIds = res.data.data;
    //     } else {
    //       console.log(res);
    //     }
    //   },
    //   complete: function () {
    //     wx.hideLoading();
    //   }
    // });
  },
  getuserInfo: function (obj, userdata, again) {
    var that = this;
    var info = that.globalData.userInfo;
    var userInfo = userdata.userInfo;
    var sex = userInfo.gender == 2 ? '女' : '男';
    wx.login({
      success(reslogin) {
        if (reslogin.code) {
          var data = {
            map: 'applet_update_member_info',
            avatar: userInfo.avatarUrl,
            nickname: userInfo.nickName,
            sex: sex,
            city: userInfo.city,
            province: userInfo.province,
            iv: userdata.iv,
            encryptedData: userdata.encryptedData,
            code: reslogin.code
          }
          console.log(data);
          if (obj.data.isupdateLoading)return;
          obj.setData({
            isupdateLoading:true
          })
          //发起请求，获取列表列表
          wx.showLoading({
            title: '加载中',
          })
          wx.request({
            url: that.globalData.requestUrl,
            data: data,
            success: function (res) {
              console.log(res.data);
              if (res.data.ec == 200) {
                that.globalData.slient = '0';
                info.avatar = userInfo.avatarUrl;
                info.nickname = userInfo.nickName;
                info.sex = sex;
                that.globalData.userInfo = info;
                that.globalData.isHasunionid = 1;
                obj.setData({
                  userInfo: info,
                  slient: that.globalData.slient,
                  isHasunionid: that.globalData.isHasunionid,
                  isupdateLoading:false
                })
                wx.showTabBar();
                console.log(obj.data.slient);
                // obj.initPage();
                if (again) {
                  if (again =='tomyGreet'){
                    obj[again]();
                  }else{
                    wx.showToast({
                      title: '同步成功',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                } else {
                  wx.hideLoading();
                }
              } else {
                app.errorTip(that, res.data.em, 2000);
              }
            },
            fail: function () {
              wx.hideLoading();
            }
          });
        }
      },
      fail:function(res){
        console.log(res);
      }
    })
  },
  makeCall: function () {
    var mobile = this.globalData.telphone;
    console.log(mobile);
    wx.showModal({
      title: '',
      content: mobile,
      confirmText: '拨打',
      confirmColor: '#48C23D',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")

            }
          })
        }
      }
    })
  },
  
  setVersion: function (obj) {
    var that = this;
    obj.setData({
      curVersion: that.globalData.version ? that.globalData.version:'',
      watermark: that.globalData.watermark ? that.globalData.watermark:'',
      supportOpen: that.globalData.supportOpen ? that.globalData.supportOpen:'',
      supportMobile: that.globalData.supportMobile ? that.globalData.supportMobile : '',
      openWatermark: that.globalData.openWatermark ? that.globalData.openWatermark:'',
      watermarkLogo: that.globalData.watermarkLogo ? that.globalData.watermarkLogo : ''
    })
  },
  //跳转设置页面授权
  openSetting: function (again) {
    var that = this;
    if (wx.openSetting) {
      wx.openSetting({
        success: function (res) {
          res.authSetting = {
            "scope.userInfo": true,
            "scope.userLocation": true,
            "scope.address": true
          }
          // that.wechatSq();
          // //尝试再次登录
          if(again){
            wx.navigateBack({
              delta:1
            })
          }else{
            // wx.reLaunch({
            //   url: '/pages/singlePage/singlePage',
            // })
            that.wechatSq();
          }
        }
      })
    } else {
      wx.showModal({
        title: '授权提示',
        content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：1、请10分钟后再次点击授权。 2、删除小程序->重新搜索进入->点击授权按钮。'
      })
    }
  },
  //设置导航条字样
  setNavtitle: function (name) {
    var that = this;
    var path = getCurrentPages()[getCurrentPages().length - 1].__route__;
    var menu = that.globalData.menuTitle;
    var title = name;
    if (!menu) {
      title = name;
    } else {
      if (!menu[path]) {
        title = name;
      } else {
        title = menu[path];
      }
    }
    console.log(title);
    wx.setNavigationBarTitle({
      title: title
    })
  },
  // 设置导航菜单
  setPageviewlink: function (obj,link) {
    var that = this;
    var path = getCurrentPages()[getCurrentPages().length - 1].__route__;
    var menu = that.globalData.pageviewlink;
    var pageviewlink = link;
    if (!menu) {
      pageviewlink = link;
    } else {
      if (!menu[path]) {
        pageviewlink = link;
      } else {
        pageviewlink = menu[path];
      }
    }
    console.log(pageviewlink);
    if (!pageviewlink){
      wx.showModal({
        title: '提示',
        content: '后台暂未配置页面链接',
        showCancel:false
      })
    }
    obj.setData({
      tempid: pageviewlink
    })
  },
  // 上传图片选择
  chooseImageTap: function (that, length, index) {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that, length, index)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, length, index)
          }
        }
      }
    })

  },
  chooseWxImage: function (type, that, length, index) {
    var _this = this;
    wx.chooseImage({
      count: length,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        var temPaths = res.tempFilePaths;
        that.setData({
          temPaths: temPaths
        });
        that.uploadImage(index);
      }
    })
  },
  // 暂停播放背景音乐
  toggleInfoPlay: function (that) {
    var _this = this;
    var isPlay = that.data.isPlay;
    console.log("切换资讯背景音乐");
    console.log(isPlay);
    if (isPlay) {
      bgMusicAudioContext.pause();
      isPlay = false;
      _this.globalData.musicPlay = false;
    } else {
      if (_this.globalData.isPlaynew == 'new') {
        console.log("新音乐播放");
        bgMusicAudioContext.stop();
        bgMusicAudioContext.src = _this.globalData.musicUrl;
        bgMusicAudioContext.coverImgUrl = _this.globalData.playMusicCover;
        bgMusicAudioContext.title = _this.globalData.musicName;

        _this.globalData.curInfoMusicid = _this.globalData.playMusicid;
        _this.musicProgress(bgMusicAudioContext, that);
        _this.globalData.isPlaynew = '';
      } else {
        bgMusicAudioContext.play();
        _this.musicProgress(bgMusicAudioContext, that);
      }
      isPlay = true;
      _this.globalData.musicPlay = true;
    }
    that.setData({
      isPlay: isPlay
    })
    _this.globalData.isPlay = isPlay;
    that.musicOpera();
  },
  // 音乐播放进度
  musicProgress: function (bgMusicAudioContext, that) {
    var _this = this;
    bgMusicAudioContext.onTimeUpdate(function () {
      var curTime = Math.ceil(bgMusicAudioContext.currentTime);
      var sumTime = Math.ceil(bgMusicAudioContext.duration);
      var curPlaytime = _this.formatPlayTime(curTime);
      var durationTime = _this.formatPlayTime(sumTime);
      that.setData({
        curTimeStep: curTime,
        curPlaytime: curPlaytime,
        sumPlayTime: sumTime,
        durationTime: durationTime,
        playProgressDis: false
      })
      _this.globalData.isReplay = '';
    });
    bgMusicAudioContext.onError(function () {
      console.log("播放错误")
      that.setData({
        isPlay: false
      })
      app.globalData.isPlay = false;
      app.globalData.curInfoMusicid = '';
    });
    bgMusicAudioContext.onEnded(function () {
      console.log("播放自然结束");
      var sumTime = Math.ceil(bgMusicAudioContext.duration);
      var durationTime = _this.formatPlayTime(sumTime);
      that.setData({
        curTimeStep: 0,
        isPlay: false,
        curPlaytime: '0:00',
        sumPlayTime: 100,
        durationTime: durationTime,
        playProgressDis: true
      })
      console.log(that.data);
      _this.globalData.isPlay = false;
      _this.globalData.isReplay = 'reply';
      _this.globalData.isPlaynew = 'new'
    })
  },
  // 获取当前定位地址
  getCurAddress: function (lat, lng, obj) {
    var that = this;
    wx.request({
      url: that.globalData.requestUrl,
      data: {
        map: 'applet_get_address',
        lat: lat,
        lng: lng
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res);
          obj.setData({
            curLocation: res.data.data.address
          })
        } else {
          that.errorTip(obj, res.data.em, 2000);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  setNavColor:function(obj){
    var that = this;
    var navColor = '#FE5A4E';
    if (that.globalData.navBgcolor&&that.globalData.navTextStyle=='white'){
      navColor = that.globalData.navBgcolor;
    }
    obj.setData({
      navColor: navColor
    })
    console.log("导航颜色" + obj.data.navColor);
  },
  setPhoneopen: function (obj) {
    var that = this;
    obj.setData({
      phoneOpen: that.globalData.phoneOpen ? that.globalData.phoneOpen:0
    })
    console.log("是否显示拨打电话" + obj.data.phoneOpen);
  },
  // 宣传海报
  requestShareinfo: function (obj,posterType) {
    var _this = this;
    var that = obj;
    //发起请求，获取列表列表
    var id = '';
    var type = that.data.goodType;
    if (type == 'group') {
      id = that.data.goodDetail.gbid;
    } else if (type == 'news') {
      id = that.data.id;
    } else {
      id = that.data.goodDetail.id;
    }
    var data = {
      map: 'applet_goods_details_poster',
      gid: id,
      type: type //普通商品good，秒杀商品seckill，拼团商品group
    }
    console.log("app.js：分销海报数据", data);
    wx.showLoading({
      title: '海报绘制中',
    })
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log("分销海报请求响应数据", res.data.data);
          var shareInfo = res.data.data;
          that.setData({
            shareInfo: shareInfo,
            shareImg: shareInfo.cover,
            shareDesc: shareInfo.shareDesc
          })
          shareInfo.type = type;
          _this.downImage(shareInfo,that,posterType);
        } else {
          _this.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        // wx.hideLoading();
      }
    });
  },
  downImage: function (shareInfo, obj,posterType) {
    var that = obj;
    var _this = this;
    if (shareInfo.cover==''){
      that.setData({
        isDrawfinish: false,
        tips: "封面不存在"
      })
      wx.hideLoading();
      return;
    }
    wx.downloadFile({
      url: shareInfo.cover,
      success: function (res1) {
        if (res1.statusCode == 200) {
          console.log(res1);
          shareInfo.cover = res1.tempFilePath;
          if (shareInfo.qrcode == '') {
            that.setData({
              isDrawfinish: false,
              tips: "小程序码不存在"
            })
            wx.hideLoading();
            return;
          }
          wx.downloadFile({
            url: shareInfo.qrcode,
            success: function (res2) {
              if (res2.statusCode == 200) {
                console.log(res2.tempFilePath);
                shareInfo.qrcode = res2.tempFilePath;
                if (shareInfo.shopLogo == '') {
                  that.setData({
                    isDrawfinish: false,
                    tips: "店主太忙了，还没来及上传LOGO。\n您可以偷偷告诉店主：\n小程序后台右上角-> 店铺设置 -> 上传店铺logo"
                  })
                  wx.hideLoading();
                  return;
                }
                wx.downloadFile({
                  url: shareInfo.shopLogo,
                  success: function (res3) {
                    console.log(res3);
                    if (res3.statusCode == 200) {
                      console.log(res3.tempFilePath);
                      shareInfo.shopLogo = res3.tempFilePath;
                      shareInfo.price = "￥" + shareInfo.price + " 扫码购买";
                      that.setData({
                        shareInfo: shareInfo
                      });
                      _this.createCanvas(that,posterType);
                    } else {
                      console.log("Logo不存在");
                      that.setData({
                        isDrawfinish: false,
                        tips: "Logo不存在"
                      })
                      wx.hideLoading();
                    }
                  },
                  fail: function () {
                    console.log("第三张图片下载失败");
                    that.setData({
                      isDrawfinish: false,
                      tips: "店主太忙了，还没来及上传LOGO。\n您可以偷偷告诉店主：\n小程序后台右上角-> 店铺设置 -> 上传店铺logo"
                    })
                    wx.hideLoading();
                  }
                })
              } else {
                console.log("小程序码不存在");
                that.setData({
                  isDrawfinish: false,
                  tips: "小程序码不存在"
                })
                wx.hideLoading();
              }
            },
            fail: function () {
              console.log("第二张图片下载失败");
              that.setData({
                isDrawfinish: false,
                tips: "小程序码下载失败"
              })
              wx.hideLoading();
            }
          })
        } else {
          console.log("封面不存在");
          that.setData({
            isDrawfinish: false,
            tips: "封面不存在"
          })
          wx.hideLoading();
        }
      },
      fail: function () {
        console.log("第一张图片下载失败");
        that.setData({
          isDrawfinish: false,
          tips: "封面下载失败"
        })
        wx.hideLoading();
      }
    })
  },
  createCanvas: function (obj,posterType) {
    var _this = this;
    var that = obj;
    var shareInfo = that.data.shareInfo;
    console.log(shareInfo);
    const ctx = wx.createCanvasContext('myCanvas');
    var winW = that.data.winW;
    var shareDesc = shareInfo.shareDesc;
    var shareDescArr = [];
    var singleTxtnum = Math.floor((winW * 0.9 * 0.8 - 30) / 15);
    if (posterType == 'distri') {
      singleTxtnum = Math.floor((winW * 0.82 - 30) / 15);
    }
    var txtLinenum = Math.ceil(shareDesc.length / singleTxtnum) <= 2 ? Math.ceil(shareDesc.length / singleTxtnum) : 2;
    for (var i = 0; i < txtLinenum; i++) {
      var length = shareDescArr.length;
      var txtObj = shareDesc.substring(length * singleTxtnum, length * singleTxtnum + singleTxtnum);
      shareDescArr.push(txtObj);
    }
    shareInfo.shareDesc = shareDescArr;
    var canvasW = winW * 0.9 * 0.8;
    var canvasH = winW * 0.9 * 0.8 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
    if (posterType == 'distri') {
      canvasW = winW * 0.82;
      canvasH = winW * 0.82 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
    }
    if (shareInfo.type == 'news') {
      canvasH = (canvasW - 30) * 14 / 25 + 30 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
    }
    that.setData({
      canvasW: canvasW,
      canvasH: canvasH
    })
    
    console.log("画布宽" + canvasW)
    if (posterType == 'distri'){
      var x = 0, y = 0, radius = 5, width = canvasW, height = canvasH;
      ctx.rect(0, 0, canvasW, canvasH)
      ctx.setFillStyle('#ffffff')
      ctx.fill()
      ctx.save()
      ctx.beginPath()
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
      ctx.clip()
    }else{
      ctx.rect(0, 0, canvasW, canvasH)
      ctx.setFillStyle('#ffffff')
      ctx.fill()
    }
    var imgW = canvasW - 30;
    var imgH = canvasW - 30;
    if (shareInfo.type == 'news') {
      imgH = imgW * 14 / 25;
    }
    console.log("图片宽" + imgW)
    ctx.drawImage(shareInfo.cover, 15, 15, imgW, imgH)
    ctx.setFontSize(15)
    for (var i = 0; i < shareDescArr.length; i++) {
      var textY = (imgH + 30) + i * 15 * 1.2 + 10;
      ctx.setFillStyle('#333333');
      ctx.fillText(shareDescArr[i], 15, textY);
    }
    var priceY = (imgH + 30) + shareDescArr.length * 15 * 1.3 + 14;
    if (shareInfo.type == 'news') {
      priceY = (imgH + 30) + shareDescArr.length * 15 * 1.3;
    }
    ctx.setFillStyle('#ff2020');
    ctx.setFontSize(15);
    if (shareInfo.type != 'news') {
      ctx.fillText(shareInfo.price, 15, priceY);
    }
    var lineY = priceY + 16;
    ctx.moveTo(20, lineY);
    ctx.lineTo(canvasW - 30, lineY);
    ctx.setStrokeStyle('#eeeeee');
    ctx.stroke();
    if (posterType == 'distri') {
      ctx.drawImage(shareInfo.qrcode, 20, lineY + 10, canvasW * 0.29, canvasW * 0.29);
      ctx.setFontSize(12);
      ctx.setFillStyle('#999999');
      ctx.setTextAlign('center');
      ctx.fillText('长按或扫码,立即购买', 20 + canvasW * 0.29 / 2, lineY + 10 + canvasW * 0.29+16);
      ctx.setFontSize(14);
      ctx.setFillStyle('#333333');
      ctx.setTextAlign('left');
      ctx.fillText(_this.globalData.userInfo.nickname, canvasW * 0.34 + 25, lineY + canvasW * 0.36 * 0.34 + 14, canvasW * 0.55);
      ctx.fillText('邀请您一起来赚钱~', canvasW * 0.34 + 25, lineY + canvasW * 0.36 * 0.32 + 24 + canvasW * 0.06);
    }else{
      ctx.drawImage(shareInfo.qrcode, 15, lineY + 10, canvasW * 0.34, canvasW * 0.36);
      ctx.setFontSize(12);
      ctx.setFillStyle('#999999');
      ctx.fillText('长按识别小程序码访问', canvasW * 0.36 + 23, lineY + canvasW * 0.36 * 0.34 + 10);
      ctx.drawImage(shareInfo.shopLogo, canvasW * 0.36 + 25, lineY + canvasW * 0.36 * 0.32 + 22, canvasW * 0.10, canvasW * 0.10);
      var shopName = shareInfo.shopName;
      var shopNameArr = [];
      var txtLinenum = Math.ceil(shopName.length / 9) <= 2 ? Math.ceil(shareDesc.length / 9) : 2;
      for (var i = 0; i < txtLinenum; i++) {
        var length = shopNameArr.length;
        var txtObj = shopName.substring(length * 9, length * 9 + 9);
        shopNameArr.push(txtObj);
      }
      if (shopName.length<=9){
        ctx.fillText(shareInfo.shopName, canvasW * 0.36 + 30 + canvasW * 0.10, lineY + canvasW * 0.36 * 0.32 + 22 + canvasW * 0.06);
      }else{
        for (var i = 0; i < shopNameArr.length; i++) {
          var textY = (lineY + canvasW * 0.36 * 0.32 + 22) + i * 12 * 1.2 + 10;
          ctx.fillText(shopNameArr[i], canvasW * 0.36 + 30 + canvasW * 0.10, textY);
        }
      }
    }
    ctx.draw();
    wx.hideLoading();
    that.setData({
      isDrawfinish: true
    })
  },
  saveImage: function (obj) {
    var _this = this;
    var that = obj;
    var canvasW = that.data.canvasW;
    var canvasH = that.data.canvasH;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: canvasW,
      height: canvasH,
      canvasId: 'myCanvas',
      fileType: 'jpg',
      success: function (res) {
        console.log(res.tempFilePath)
        var tempFilePathShow = res.tempFilePath;
        wx.showLoading({
          title: '正在保存',
          mask: true,
          time: 100000
        })
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePathShow,
          success(res) {
            console.log(res);
            _this.errorTip(that, "图片保存成功", 2000);
          },
          fail(f) {
            _this.errorTip(that, "图片保存失败", 2000);
          },
          complete() {
            wx.hideLoading();
          }
        })
      }
    })
  },
  // 广告数据
  requestAd: function (obj) {
    var _this = this;
    var that = obj;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_city_advertisement_cfg'
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          var randomIndex = Math.round(Math.random() * (10 - 1) + 1) - 1;
          that.setData({
            adInfo: res.data.data,
            randomIndex: randomIndex
          })
        } else {
          console.log(res.data)
        }
      },
      complete: function () {
      }
    });
  },
  getContactCfg: function () {
    var _this = this;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_kefu_cfg'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log('获取客服配置信息', res.data.data);
          wx.setStorage({
            key: 'contactCfg',
            data: res.data.data,
            success: function (res) {
              console.log('存储成功');
              if (_this.globalData.againRequestContact && getCurrentPages()) {
                var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针 
                _this.contactData(page);
                _this.globalData.againRequestContact = false;
              }
            },
            fail: function () {
              console.log('存储失败');
            }
          })
        } else {
        }
      },
      complete: function () {

      }
    });
  },
  //客服验证绑定手机号
  contactData: function (that) {
    var _this = this;
    var data = wx.getStorageSync('contactCfg')
    if (data) {
      console.log('获取到客服缓存配置', data);
      that.setData({
        kefuSetting: data
      })
    } else {
      console.log('重新获取客服缓存配置');
      _this.globalData.againRequestContact = true;
      _this.getContactCfg();
    }
  },
  contactRecord: function (e) {
    var _this = this;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_kefu_click'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log(res.data.data);
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
    console.log(e);
    if (e.detail.path) {
      let navUrl = e.detail.path + "?";
      for (let i in e.detail.query) {
        navUrl += (i + '=' + e.detail.query[i] + '&');
      };
      console.log(navUrl);
      wx.navigateTo({
        url: navUrl,
      })
    }
  },
  getPhone: function (e,that) {
    var _this = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var data = {
            map: 'applet_bind_member_mobile',
            code: res.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          };
          if (data.encryptedData && data.iv) {
            _this.requestMobile(that,data);
          }
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  requestMobile: function (that,data) {
    console.log(data);
    var _this = this;
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    console.log(_this.globalData.requestUrl);
    console.log(data);
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log(res.data.data);
          _this.globalData.contactPhone = res.data.data;
          that.setData({
            contactPhone: res.data.data
          })
        } else {
          _this.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
  },
  isAudit: function (that, url, func) {
    var _this = this;
    // var indexUrl = '';
    // if (url) {
    //   indexUrl = decodeURIComponent(url);
    // }
    // 判断是否验证
    var data = {
      map: 'applet_start_page'
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url:  _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log("审核页面")
        console.log(res.data.data);
        var applyInfo = res.data.data;
        that.setData({
          applyInfo: applyInfo,
          applyStatus: applyInfo.applyStatus
        })
        console.log("验证状态" + (applyInfo.applyStatus == 2))
        if (applyInfo.applyOpen == 1){
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }else{
          if (func) {
            func();
          }
        }
        // if (applyInfo.applyStatus == 2) {
        //   // var indexUrl = applyInfo.indexUrl;
        //   // if (url){
        //   //   indexUrl = decodeURIComponent(url);
        //   // }
        //   // console.log("审核前页面路径" + indexUrl)
        //   // wx.reLaunch({
        //   //   url: indexUrl
        //   // })
        //   if(func){
        //     func();
        //   }
        // }
        // var applyTtitle = applyInfo.applyTtitle ? applyInfo.applyTtitle : '申请验证';
        // console.log(applyTtitle);
        // _this.setNavtitle(applyTtitle);
      },
      fail: function (res) {
        console.log(res.data);
        _this.errorTip(that, res.data.em, 2000);
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  setCartnum:function(){
    var that = this;
    if (!that.globalData.plumSession) return;
    var menu = that.globalData.menuTitle;
    var cartIndex = '';
    cartIndex = that.globalData.cartIndex;
    console.log("当前购物车索引");
    if (!menu){
      cartIndex = 1;
    }
    console.log(cartIndex);
    if (cartIndex!=''){
      console.log('购物车数量11111111', that.globalData.requestCartNum);
      if (that.globalData.requestCartNum>=0){
        if (that.globalData.requestCartNum>0){
          wx.setTabBarBadge({
            index: cartIndex,
            text: that.globalData.requestCartNum.toString()
          });
        } else if (that.globalData.requestCartNum==0){
          wx.removeTabBarBadge({
            index: cartIndex
          })
        }
        return;
      }
      wx.request({
        url: that.globalData.requestUrl,
        data: {
          map: 'applet_cart_num'
        },
        success: function (res) {
          // console.log(res.data.data.cartNum);
          var cartNum = res.data.data?res.data.data.cartNum:0;
          if (cartNum>0){
            wx.setTabBarBadge({
              index: cartIndex,
              text: cartNum.toString()
            })
          }else{
            wx.removeTabBarBadge({
              index: cartIndex
            })
          }
        },
        fail: function (res) {
          console.log(res.data);
        },
      });
    }
  },
  // 返回首页跳转判断
  backHome:function(){
    var _this = this;
    var pathArr = getCurrentPages();
    if (pathArr.length <= 1) {
      wx.reLaunch({
        url: '/pages/singlePage/singlePage'
      })
    } else {
      if (_this.globalData.homePath){
        _this.getHomepath(pathArr);
      }else{
        wx.request({
          url: _this.globalData.requestUrl,
          data: {
            map: 'applet_index_page',
            appletType: 1
          },
          success: function (res) {
            var homePath = res.data.data.path;
            console.log(homePath);
            _this.globalData.homePath = homePath;
            _this.getHomepath(pathArr);
          }
        });
      }
    }
  },
  // 返回首页获取配置首页路径跳转
  getHomepath: function (pathArr){
    var _this = this;
    var ishasHome = false;
    var homePath = _this.globalData.homePath;
    for (let i = 0; i < pathArr.length; i++) {
      if (pathArr[i].__route__ == homePath) {
        ishasHome = true;
      }
    }
    console.log(ishasHome);
    if (ishasHome) {
      wx.navigateBack({
        delta: 10
      })
    } else {
      wx.switchTab({
        url: '/' + homePath
      })
    }
  },
  getUnionid: function (that, userdata) {
    var _this = this;
    wx.login({
      success(res) {
        if (res.code) {
          var data = {
            map: 'applet_get_member_unionid',
            code: res.code,
            iv: userdata.iv,
            encryptedData: userdata.encryptedData
          };
          console.log(data);
          //发起请求，获取列表列表
          wx.request({
            url: _this.globalData.requestUrl,
            data: data,
            success: function (res) {
              console.log(res.data);
              if (res.data.ec == 200) {
                _this.globalData.isHasunionid = 1;
                if(that){
                  that.setData({
                    isHasunionid: _this.globalData.isHasunionid
                  })
                }
                
              } else {
              }
            },
            complete: function () {
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  requestIndex: function (type) {
    var that = this;
    wx.request({
      url: that.globalData.requestUrl,
      data: {
        map: 'applet_index_info',
        version: that.globalData.version,
        base: that.globalData.base,
        couponIndex: 0
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.globalData.distribOpen = res.data.data.distribOpen;
          var sharedata = {
            shareOpen: res.data.data.shareOpen,
            shareUrl: res.data.data.shareUrl,
            shareTitle: res.data.data.template.title
          }
          that.globalData.sharedata = sharedata;
          // 存储是否开启客服
          that.globalData.customerService = res.data.data.customerService;
          if (res.data.data.customerService == 1) {
            var sessionForm = {
              "nickName": that.globalData.userInfo.nickName,
              "city": that.globalData.userInfo.city
            }
            that.globalData.sessionForm = JSON.stringify(sessionForm);
          }
          // 设置电话
          that.globalData.telphone = res.data.data.mobile;
          that.globalData.phoneOpen = res.data.data.phoneOpen;
          var namelogo = {
            name: res.data.data.name,
            logo: res.data.data.logo
          };
          that.globalData.namelogo = namelogo;
          var shareInfo = {
            shareCover: res.data.data.shareCover,
            shareTitle: res.data.data.shareTitle
          }
          that.globalData.shareInfo = shareInfo;
          var shopname = res.data.data.name;
          wx.setStorage({
            key: "shopInfoname",
            data: shopname,
            success: function (e) {
              console.log("存储成功")
            }
          })
        } else {
        }
      },
      complete: function () {
      }
    });
  },
  //订阅消息，获取模版id
  getSubId: function (obj,operate,fun){
    var that = this;
    console.log(operate);
    var tmplIdsArr = Object.keys(that.globalData.requestTmplIds);
    console.log(tmplIdsArr.length)
    if (that.globalData.requestTmplIds && tmplIdsArr.length>0){
      var tmplData = that.globalData.requestTmplIds;
      var tmplIds = [];
      tmplIds = tmplData[operate];
      if (wx.canIUse('requestSubscribeMessage')) {
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            console.log('调起成功', res);
            var ids = [];
            for (let key in res) {
              console.log(key, res[key]);
              console.log(res[key]);
              if (res[key] == 'accept') {
                ids.push(key);
              }
            }
            if (ids.length > 0) {
              that.saveSubId(ids); //存储同意的ids
            }
          },
          fail(res) {
            console.log('调起失败', res);
          },
          complete() {
            obj[fun]();
          }
        })
      }else{
        obj[fun]();
      }
    }else{
      obj[fun]();
    }
  },
  //处理保存同意发送消息的id
  saveSubId:function(ids){
    var that = this;
    var saveTmplNum = that.globalData.saveTmplNum;
    var saveTmplArr = that.globalData.saveTmplArr;
    console.log(saveTmplNum);
    if (saveTmplNum>10){
      that.toSaveSubId();//执行保存操作
    }else{
      saveTmplNum+=1;
      that.globalData.saveTmplNum = saveTmplNum;
      var tmplArr = that.globalData.saveTmplArr;
      console.log(tmplArr);
      for (let i = 0; i < ids.length; i++){
        let keyIndex = -1;
        for (let key in tmplArr) { //判断之前存储的数组是否含有这个订阅id
          if (key == ids[i]) {
            keyIndex = ids[i];
          } 
        }
        if(keyIndex!=-1){ //之前存在的订阅id累加1
          tmplArr[keyIndex] += 1;
        }else{ //不存在的新增一项
          tmplArr[ids[i]] = 1;
        }
       
      }
      console.log(tmplArr);
      that.globalData.saveTmplArr = tmplArr;
    }
  },
  //保存同意发送消息的id
  toSaveSubId:function(){
    var that = this;
    console.log('保存订阅id');
    var saveTmplArr = that.globalData.saveTmplArr;
    var saveTmplArrLen = Object.keys(saveTmplArr);
    if (saveTmplArrLen.length>0){
      console.log('执行保存订阅id');
      wx.request({
        url: that.globalData.requestUrl,
        data: {
          map: 'applet_subscribe_save_auth',
          tplIds: JSON.stringify(saveTmplArr)
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            console.log('保存订阅消息成功');
            that.globalData.saveTmplNum = 0;
            that.globalData.saveTmplArr = {};
          } else {
            console.log('保存订阅消息失败1');
          }
        },
        fail: function (res) {
          console.log('保存订阅消息失败2');

        },
        complete: function () {
        }
      });
    }
    console.log(that.globalData.saveTmplArr);
  }
}